package com.jg.tool.actable.db;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.jg.tool.actable.db.po.FieldStructure;

import java.sql.Connection;
import java.util.List;

/**
 * sqlite执行器
 * @author gaolj
 */
public class SqliteDbExecutor extends AbstractDbExecutor {
    public SqliteDbExecutor(Connection connection) {
        super(connection);
    }

    @Override
    public boolean checkTableIsExists(String tableName) {
        String sql = "select count(1) as ct from sqlite_master where type='table' and name = '" + tableName + "'";
        List<Entity> entityList = query(sql);
        int ct = entityList.get(0).getInt("ct");
        return ct > 0;
    }

    @Override
    public boolean checkTableFieldIsExists(String tableName, String fieldName) {
        String sql = "PRAGMA table_info('" + tableName + "')";
        List<Entity> entityList = query(sql);
        for (Entity entity : entityList) {
            String name = entity.getStr("name");
            if (fieldName.equalsIgnoreCase(name)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public FieldStructure getFieldStructure(String tableName, String fieldName) {
        String sql = "PRAGMA table_info('" + tableName + "')";
        List<Entity> entityList = query(sql);
        if (entityList == null || entityList.size() <= 0) {
            return null;
        }
        for (Entity entity : entityList) {
            String name = entity.getStr("name");
            if (fieldName.equalsIgnoreCase(name)) {
                FieldStructure fieldStructure = new FieldStructure();
                fieldStructure.setName(fieldName);
                String dataType = entity.getStr("type").toLowerCase();
                fieldStructure.setType(dataType);
                String nullable = entity.getStr("notnull");
                if ("1".equals(nullable)) {
                    fieldStructure.setNull(true);
                } else {
                    fieldStructure.setNull(false);
                }
                String columnKey = entity.getStr("pk");
                if ("1".equals(columnKey)) {
                    fieldStructure.setKey(true);
                } else {
                    fieldStructure.setKey(false);
                }
                String defaulValue = entity.getStr("dflt_value");
                fieldStructure.setDefaultValue(defaulValue);
                return fieldStructure;
            }
        }
        return null;
    }

    @Override
    public void modifyField(String tableName, List<String> fieldSqlList) {
        //sqlite不支持修改列
    }

    @Override
    public boolean checkIndexIsExists(String tableName, String indexName) {
        return true;
    }

}
